import router from './routers'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import { buildMenus } from '@/api/system/menu'
import { filterAsyncRouter } from '@/store/modules/permission'

NProgress.configure({ showSpinner: false })// NProgress Configuration

// const whiteList = ['/login']// no redirect whitelist 注意加上“/”
const whiteList = ['/', '/front', '/login', '/frontNotice', '/frontCompany', '/frontCar', '/frontBookDetail']

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    console.log('登录有权限')
    if (to.path === '/backHome') {
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => { // 拉取user_info
          // 动态路由，拉取菜单
          console.log('拉取菜单1')
          loadMenus(next, to)
        }).catch((err) => {
          console.log(err)
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        // 登录时未拉取 菜单，在此处拉取，走这里
      } else if (store.getters.loadMenus) {
        // 修改成false，防止死循环
        store.dispatch('updateLoadMenus').then(res => {})
        console.log('拉取菜单2')
        loadMenus(next, to)
      } else {
        next()
      }
    } else {
      next(next, to)
      NProgress.done()
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1 && to.path === '/') { // 在免登录白名单，直接进入
      console.log('白名单')
      next()
    } else if (whiteList.indexOf(to.path) !== -1) {
      console.log('重定向')
      // next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      next(next, to)
      NProgress.done()
    } else {
      // 否则全部重定向到首页
      next(`/?redirect=${to.path}`)
      NProgress.done()
    }
  }
  console.log('to.path==>', to.path)
  console.log('to.path==>', from)
  console.log('to.path==>', next)
  /* has no token*/
  // if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
  //     next()
  // } else {
  //     next(`/?redirect=${to.path}`) // 否则全部重定向到登录页
  //     NProgress.done()
  // }
})

export const loadMenus = (next, to) => {
  buildMenus().then(res => {
    const asyncRouter = filterAsyncRouter(res)
    asyncRouter.push({ path: '*', redirect: '/404', hidden: true })
    store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
      router.addRoutes(asyncRouter) // 动态添加可访问路由表
      next({ ...to, replace: true })
    })
  })
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
